"""
get_h3c_filestorage_dirs()函数负责调用华三存储api，返回所有存储目录
结果：
{"data": [ {"{#DIR}": "webapp"}, {"{#DIR}": "webdevsvn"}, {"{#DIR}": "webserver"}]}
"""
# -*- coding:utf-8 -*-


import requests
import json
import re


# 调用华三集群的API，返回所有存储目录
def get_h3c_filestorage_dirs():
    # 拼接成登陆url
    base_url = "http://地址"
    request_url = "/api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username": "xx", "password": "xx"}

    # 登录请求
    res = requests.post(url=url, data=json.dumps(data), headers={'content-type': "application/json"})

    # 获取响应头信息
    set_cookie = res.headers.get('Set-Cookie')
    text_set_cookie = re.split('[;,=\']', set_cookie)

    # 从响应头信息中提取后面访问需要的cookie_value和x_xsrf_token_value
    xsrf_token_value = text_set_cookie[1].strip()

    cookie_value = 'calamari_sessionid=' + text_set_cookie[12] + ';' + 'XSRF-TOKEN=' + xsrf_token_value

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url

    cluster_res = requests.get(
        url=cluster_id_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成请求URL
    filestorage_dirs_url_1 = "/api/v3/onestor/"
    filestorage_dirs_url_2 = "/filestorage/dirs"
    filestorage_dirs_url = base_url + filestorage_dirs_url_1 + cluster_id + filestorage_dirs_url_2

    # 请求参数
    request_data = {
        "path": "/",
        "start": 1,
        "filter_file": "all"
    }

    # 发送POST请求，得到返回数据
    filestorage_dirs_res = requests.post(
        url=filestorage_dirs_url,
        data=json.dumps(request_data),
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })
    filestorage_dirs_data = filestorage_dirs_res.json()

    data_list = []
    for path in filestorage_dirs_data['data']['content']:
        data_volume_dict = {}
        data_volume_dict['{#DIR}'] = path['name']
        data_list.append(data_volume_dict)

    data_all_volume_dict = {}
    data_all_volume_dict['data'] = data_list
    data_all_volume_json = json.dumps(data_all_volume_dict)

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
        url=logout_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })
    return data_all_volume_json


if __name__ == '__main__':
    h3c_xd_dict_data = get_h3c_filestorage_dirs()
    print(h3c_xd_dict_data)